package com.hyl.servlet.impl;

import com.hyl.entity.Person;
import com.hyl.service.PersonService;
import com.hyl.service.PersonServiceImpl;
import com.hyl.servlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Description TODO
 * @Author hyl
 * @Date 2023/4/26 8:59
 **/
public class PersonServlet implements BaseServlet {

	public String list(HttpServletRequest request,HttpServletResponse response){
		//1、获取用户请求
		//2、操作=》service
		PersonService service = new PersonServiceImpl();
		List<Person> list =  service.findAll();

		request.setAttribute("personList",list);
		//3、页面跳转
		//request.getRequestDispatcher("index.jsp").forward(request, response);
		return "dispatcher:index.jsp";
	}

	public String add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1、获取用户请求
		request.setCharacterEncoding("utf-8");
		String name= request.getParameter("name");
		String sex= request.getParameter("sex");
		Integer age= Integer.valueOf(request.getParameter("age"));
		String rank= request.getParameter("rank");
		String department= request.getParameter("department");
		//2、操作=》service
		Person tmp = new Person(null,  name,  sex,  age,  rank,  department);
		PersonService service = new PersonServiceImpl();
		int ret = service.add(tmp);
		//3、页面跳转
		return "out:"+"";

	}

	public String  del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1、获取用户请求
		String id= request.getParameter("id");

		//2、操作=》service
		PersonService service = new PersonServiceImpl();
		int ret = service.del(Integer.valueOf(id));
		//3、页面跳转
//		response.setCharacterEncoding("utf-8");
//		response.setContentType("text/html;charset=UTF-8");
//		PrintWriter out = response.getWriter();//响应结果：服务器==》客户端
//		out.print(ret>0?"ok":"err");
//		out.close();

		return "out:"+(ret>0 ? "ok" : "err");

	}


	public String update(){
		return null;
	}

	public  String check(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1、获取用户请求
		String name = request.getParameter("name");
		//2、操作=》service
		PersonService service = new PersonServiceImpl();
		int ret = service.checkName(name);
		//3、页面跳转
//		response.setCharacterEncoding("utf-8");
//		response.setContentType("text/html;charset=UTF-8");
//		PrintWriter out = response.getWriter();//响应结果：服务器==》客户端
//		out.print(ret>0 ? "ok" : "err");
//		out.close();

		return "out:"+(ret>0 ? "ok" : "err");

	}
}
